package com.aigou.admin.controller;

import com.aigou.admin.entity.Product;
import com.aigou.admin.service.ProductService;
import com.aigou.admin.service.impl.ProductServiceImpl;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/findAllProducts")
public class FindAllProductController extends HttpServlet {

    //调用service层方法
    private ProductService productService = new ProductServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 设置请求和响应的字符编码为UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=UTF-8");

        //查询用户
        List<Product> products = productService.getAllProducts();
        //转换为JSON，通过流发送给客户端
        JSONObject responseJson = new JSONObject();
        responseJson.put("status", "success");
        responseJson.put("message", "Product found");
        responseJson.put("data", products);
        response.getWriter().write(responseJson.toJSONString(JSONWriter.Feature.PrettyFormat));
    }
}